package com.atguigu.acl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.atguigu.acl.entity.Resource;
import com.atguigu.acl.mapper.ResourceMapper;
import com.atguigu.acl.service.AdminCacheService;
import com.atguigu.acl.service.ResourceService;
import com.atguigu.utils.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author smday
 * @since 2020-08-10
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements ResourceService {

    @Autowired
    private AdminCacheService adminCacheService;

    @Override
    public List<Resource> listAll() {
        return baseMapper.selectList(null);
    }

    @Override
    public int create(Resource resource) {
        return baseMapper.insert(resource);
    }

    @Override
    public int update(Long id, Resource resource) {
        resource.setId(id);
        int count = baseMapper.updateById(resource);
        adminCacheService.delResourceListByResource(id);
        return count;
    }

    @Override
    public Resource getItem(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public int delete(Long id) {
        int count = baseMapper.deleteById(id);
        adminCacheService.delResourceListByResource(id);
        return count;
    }

    @Override
    public Map<String, Object> list(Long categoryId, String nameKeyword, String urlKeyword, Integer pageSize, Integer pageNum) {
        Page<Resource> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Resource> wrapper = new QueryWrapper<>();
        if (categoryId != null) {
            wrapper.eq("category_id", categoryId);
        }
        if (StrUtil.isNotEmpty(nameKeyword)) {
            wrapper.like("name", nameKeyword);
        }
        if (StrUtil.isNotEmpty(urlKeyword)) {
            wrapper.like("url", urlKeyword);
        }
        baseMapper.selectPage(page, wrapper);
        return PageUtils.convertPageToMap(page);
    }
}
